package com.woniuxy.aop;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.utils.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.woniuxy.entity.InfoLog;
import com.woniuxy.producer.DelayExchangeProducer;
import com.woniuxy.service.IInfoLogService;
import com.woniuxy.util.CONSTANT;
import com.woniuxy.util.GetUserContent;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @author：xurice
 * @date：Created in 2024/3/2 9:37
 * @description：
 */
@Aspect
@Component
@Slf4j
public class LogAdvice {

    @Autowired
    IInfoLogService iInfoLogService;

    //消息队列生产者
    @Autowired
    private DelayExchangeProducer delayExchangeProducer;
    @Around("@annotation(com.woniuxy.anno.LogAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        String username = "未登录人员";

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String jwt = request.getHeader("thoken");
        if (!StringUtils.isEmpty(jwt)){
            Map userInfo = GetUserContent.getUserInfo();
            username = (String) userInfo.get(CONSTANT.ACCOUNT);
        }
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Date startTime = new Date();
        //执行方法
        Object proceed = joinPoint.proceed(args);
        Date endTime = new Date();

        InfoLog log = new InfoLog();
        log.setClassName(className);
        log.setUsername(username);
        log.setMethodName(methodName);
        log.setRunTime(endTime.getTime()-startTime.getTime());
        log.setEndTime(endTime);
        log.setStartTime(startTime);

        delayExchangeProducer.send(JSON.toJSONString(log),"addLogQueue",0);

        return proceed;
    }
}
